#include "stdafx.h"
#include "config/Def.h"
#include "File.h"
#include "debug/Debug.h"
#include <fstream>
#include <sys/stat.h>
#include "platform/Device.h"

using namespace unigame;

File::File(const char* name, int32u type):
m_size(0),
m_data(0),
m_type(type)
{
    int32u len = strlen(name) + 1;
    char* path = 0;
    switch (m_type)
    {
        case E_RESOURCE_FT:
            len += Device::currentDevice()->getResourcePathLength();
            path = Device::currentDevice()->getResourcePath();
            break;
		case E_SAVE_FT:
			len += Device::currentDevice()->getSavePathLength();
			path = Device::currentDevice()->getSavePath();
        case E_TEMP_FT:
        default:
            break;
    }
    m_name = uni_new char[len];
    sprintf(m_name, "%s%s", path, name);
}

File::~File()
{
    uni_delete_array(m_name);
    uni_delete_array(m_data);
}

void File::read()
{
    std::ifstream fis;
    fis.open(m_name);
    if(!fis)
    {
        Debug::log(m_name);
        assert(false && "file open failed");
    }
    struct stat info;
    stat(m_name, &info);
    
    m_size = info.st_size;
    if(m_data)
    {
        delete[] m_data;
    }
    m_data = uni_new char[m_size];
    fis.read(m_data, m_size);
    fis.close();
}

void File::close()
{
    uni_delete_array(m_data);
}

void File::write(char *data, int32u len)
{
    std::ofstream fos;
    fos.open(m_name);
    if(!fos)
    {
        Debug::log(m_name);
        assert(false && "file open failed");
    }
    fos.write(data, len);
    fos.flush();
    fos.close();
}